package com.mnxiaotu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mnxiaotu.common.vo.Result;
import com.mnxiaotu.entity.Menu;
import com.mnxiaotu.entity.UserRole;
import com.mnxiaotu.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 系统权限菜单控制器
 * @author 86182
 */
@RestController
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 查询所有菜单列表
     * @param null
     * @return
     */
    @RequestMapping("/treeList")
    @PreAuthorize("hasAnyAuthority('system:menu:query')")
    public Result treeList(){
        List<Menu> menuList = menuService.list(new QueryWrapper<Menu>().orderByAsc("order_num"));
        return Result.ok().put("treeMenu",menuService.buildTreeMenu(menuList));
    }

    /**
     * 添加或修改
     * @param menu
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('system:menu:add')"+"||"+"hasAnyAuthority('system:menu:edit')")
    public Result save(@RequestBody Menu menu){
        if (menu.getId()==null || menu.getId() == -1){
            menu.setCreateTime(new Date());
            menuService.save(menu);
        }else {
            menu.setUpdateTime(new Date());
            menuService.updateById(menu);
        }
        return Result.ok();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('system:menu:query')")
    public Result findById(@PathVariable(value = "id")Long id){
        Menu menu = menuService.getById(id);
        Map<String,Object> menuList = new HashMap<>();
        menuList.put("menu",menu);
        return Result.ok(menuList);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public Result delete(@PathVariable(value = "id")Long id){
        int count = menuService.count(new QueryWrapper<Menu>().eq("parent_id",id));
        if(count>0){
            return Result.error("请先删除子菜单！");
        }
        menuService.deleteById(id);
        return Result.ok();
    }
}
